<?php

include_once('ccl_controller.php');

class authenticate extends ccl_controller
{
	function __construct()
	{
		// Call the Model constructor
		parent::__construct();
		
		// Load database with "admin" permissions
		$this->load->database('admin');
		
		// Load sidebar
		$this->data['sidebar'] = $this->load->view('public/intranet/sidebar', $this->data, true);
	}

	public function login()
	{
		// If 'POST' data exists (i.e. the submit button was clicked)
		if ( $this->input->post() )
		{
			// Load the form validation library and set validation rules
			$this->load->library('form_validation');
			$this->form_validation->set_rules('username', 'Username', 'required');
			$this->form_validation->set_rules('password', 'Password', 'required');

			// If form validation fails, load login page again
			if ( $this->form_validation->run() )
			{
				// Get username and password from form
				$username = $this->input->post('username');
				$password = sha1($this->input->post('password'));
			
				// Load the "Actor" model and run query to search "actor" table to find rows that match the username and password entered
				$this->load->model('users_model');
				$query = $this->users_model->getUserByUsernameAndPassword( $username, $password );
				
				// If a row is returned, then login is correct. Redirect to homepage and terminate script
				if ( $query->num_rows() )
				{
					$this->session->set_userdata('CurrentUser', $query->row() );
					if ( $this->session->userdata('CurrentUser')->admin_access )
					    redirect('admin/admin');
					
					else if ( $this->session->userdata('CurrentUser')->staff_access )
					    redirect('staff/staff');
					
					redirect('public/intranet');
				}
				
				// Set error variable
				$this->data['error'] = 'Incorrect username and/or password';
			}
		}
		
		// Load the "authenticate" view
		$this->data['main_content'] = $this->load->view('login', $this->data, true);
		
		// Load $this->data['main_content'] in the main template
		$this->load->view($this->template, $this->data);
	}

	public function logout()
	{
		// Unset 'CurrentUser'
		$this->session->unset_userdata('CurrentUser');
		
		// Redirect to home
		redirect('public/intranet/');
	}
}

?>